// pages/shops/shops.js
const service = require("../../module/service.js");
const get_from = require("../../module/service").get_from;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shop_data: {},
    banner_urls: [],
    shop_list: [],
    food_list: [],
    is_search: false,
    paddingTop: 20,
    triggered: false,
    goods: [],
    shops: [],
    padding: [0, 16, 0, 16],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow(options) {
    // 获取轮播图
    get_from("shop/getHomePageBanners").then((res)=>{
      this.setData({
        banner_urls: res.data
      });
    })
    //请求数据
    get_from("shop/shop_data").then((res) => {
      console.log(res.data)
      this.setData({
        shop_data: res.data,
        shop_list: res.data.shops,
        is_search: false
      })
    }).catch(() => {
      wx.showToast({
        title: '数据请求错误',
        icon: 'error',
        duration: 500
      })
    });

  },

  toShop: function (e) { //根据id导航到商店并加载对应id的商店信息
    getApp().globalData.curr_shop_id = e.currentTarget.dataset.id;
    // console.log(getApp().globalData.shopInfo.curr_shop_id);
    // let banner_urls = e.currentTarget.dataset.banner_urls;
    wx.navigateTo({
      url: '../../pages/index/index?shop_id=' + e.currentTarget.dataset.id,
    });
  },

  // 可以搜索食堂，也可以搜索菜品
  searchSubmit: function (e) {
    let shop_name = e.detail.value.shop_name;
    let search_item = {name: shop_name};
    console.log(search_item);
    get_from("shop/shop_data", search_item).then((res)=>{
      // 接收一个列表，这个列表的内容里面同时包含菜品和商店信息，以is_shop字段区分，
      // 然后分别展示出来
      console.log(res.data)
      let shop_list = [];
      let food_list = [];
      let res_len = 0;
      res_len = res.data.shops.length;
      // 将结果分别存放与shop_list和food_list中
      for (let i=0; i<res_len; i++)
      {
        console.log(res.data.shops[i])
        if (res.data.shops[i].is_shop == 1)
        {
          shop_list.push(res.data.shops[i])
        }
        else if (res.data.shops[i].is_shop == 0)
        {
          food_list.push(res.data.shops[i])
        }
      }

      this.setData({
        shop_data: res.data,
        shop_list: shop_list,
        food_list: food_list,
        is_search: true
      })
    }).catch(() => {
      wx.showToast({
        title: '数据请求错误',
        icon: 'error',
        duration: 500
      })
    });
  },

  // 跳转到商品详情页面
  toFood(e){
    let food_id = e.currentTarget.dataset.id
    let shop_id = e.currentTarget.dataset.shop_id

    getApp().globalData.curr_shop_id = shop_id

    //跳转
    wx.navigateTo({
      url: '/pages/fdetail/fdetail?food_id=' + food_id + '&translist_id=-1',
    });
  }
})